<template>
  <el-dialog :title="isEdit?'修改角色':'新增角色'" :visible.sync="visible"
             @close="$emit('update:show', false)" width="600px">
    <el-form label-width="auto" :rules="rules" :model="params" ref="editForm" size="small">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本信息" name="first">
          <el-form-item label="角色名称" prop="name">
            <el-input placeholder="请输入名称，例:管理员" v-model="params.name">
            </el-input>
          </el-form-item>
          <el-form-item label="角色代码" prop="code">
            <el-input placeholder="请输入角色代码，例:sysmanagement" v-model="params.code"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-switch
              v-model="params.state"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="启用">
            </el-switch>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="分配权限" name="second" :disabled="!isEdit">
          <permission-tree-table v-model="bindedPermids"></permission-tree-table>
        </el-tab-pane>
        <el-tab-pane label="授权接口" name="third" :disabled="!isEdit">
        <auth-api-mod v-if="roleData" :auth-id="roleData.id" auth-type="role" @change="authApiChange"></auth-api-mod>
        </el-tab-pane>
      </el-tabs>

      <!--<el-form-item label="权限">-->
      <!--<el-card shadow="never" style="height: 150px;overflow: auto;">-->
      <!--<el-tree ref="permTree"-->
      <!--:props="permTreeDataProps"-->
      <!--node-key="id"-->
      <!--:data = "permsData"-->
      <!--show-checkbox-->
      <!--:default-expand-all="true"-->
      <!--:check-strictly="true"-->
      <!--:default-checked-keys="bindedPermids"-->
      <!--@check-change="checkBindPerms">-->
      <!--<span class="custom-tree-node" slot-scope="{ node, data }">-->
      <!--<span>{{ node.label }}</span>&nbsp;<span class="text-danger">{{ data.available===0?'[禁用]':'' }}</span>-->
      <!--</span>-->
      <!--</el-tree>-->
      <!--</el-card>-->
      <!--<el-button type="text" @click="checkAll()">全选</el-button>-->
      <!--<el-button type="text" @click="checkAll(false)">取消全选</el-button>-->
      <!--</el-form-item>-->

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="loading" @click="save">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import PermissionTreeTable from '../../common/PermissionTreeTable'
  import AuthApiMod from '../common/AuthApiMod'

  export default {
    name: "AddEditRoleDialog",
    props: ['show', 'roleData'],
    components: {
      PermissionTreeTable,
      AuthApiMod
    },
    watch: {
      show() {
        this.visible = this.show;
        this.api.post('/bucket-system/system/resources/all', {})
          .then((data) => {
            this.parseDatas(data.data);
            this.bindedPermids = [];

            this.permsData = data.data;
          });
      },
      roleData: {
        handler() {
          if (this.roleData) {
            let ps = this.roleData.resourcesId;
            if (ps) {
              for (let i = 0; i < ps.length; i++) {
                this.bindedPermids.push(ps[i]);
              }
            }
            let sids = this.roleData.systemId;
            if (sids) {
              sids.forEach((item) => {
                this.bindedSystemids.push(item);
              });
            }

            for (let k in this.params) {
              this.params[k] = this.roleData[k] ? this.roleData[k] : null;
            }
            this.isEdit = true;
          } else {
            for (let k in this.params) {
              this.params[k] = '';
            }
            this.params.state = 1;
            this.isEdit = false;
          }
        },
        immediate: true,
        deep: true
      }
    },
    data() {
      return {
        activeName: 'first',
        visible: this.show,
        isEdit: false,
        loading: false,
        params: {
          id: '',
          name: '',
          code: '',
          resourcesId: [],
          systemId: [],
          state: 1
        },
        rules: {
          name: [
            {required: true, message: '角色名称不能为空', trigger: 'blur'}
          ],
          code: [
            {required: true, message: '角色代码不能为空', trigger: 'blur'}
          ]
        },
        // 权限树菜单部分
        permTreeDataProps: {
          label: 'text',
          children: 'children'
        },
        permsData: [],
        bindedPermids: [],
        bindedSystemids: [],
        allIds: [],
        selectedApis: []
      }
    },
    mounted: function () {

    },
    methods: {
      save: function () {
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            let _url = '';
            if (!this.isEdit) {
              _url = '/bucket-system/system/role/add';
            } else {
              _url = '/bucket-system/system/role/update';
            }
            this.params.resourcesId = this.bindedPermids;
            this.params.systemId = this.bindedSystemids;
            this.loading = true;
            this.api.post(_url, this.params)
              .then((data) => {
                this.loading = false
                if (data.code === 200) {
                  if (this.selectedApis.length > 0)
                    this.saveAuthApis();

                  this.visible = false;
                  this.$message({
                    message: '保存成功',
                    type: 'success'
                  });
                  this.$parent.query();
                } else {
                  this.$message.error(data.data);
                }
              }).catch((error) => {
              this.loading = false;
            });
          } else {
            return false;
          }
        });
      },
      checkBindPerms: function (data, checked, indeterminate) {
        this.bindedPermids = (this.$refs.permTree.getCheckedKeys());
      },
      parseDatas: function (list) {
        for (let i = 0; i < list.length; i++) {
          this.allIds.push(list[i].id);
          this.parseDatas(list[i].children);
        }
      },
      checkAll: function (uncheck) {
        if (uncheck === false)
          this.$refs.permTree.setCheckedKeys([]);
        else
          this.$refs.permTree.setCheckedKeys(this.allIds);
      },
      saveAuthApis() {
        this.api.post('/bucket-system/gateway/api/interface/bind', {
          authId: this.roleData.id, authType: 'role', intId: this.selectedApis.join(',')
        });
      },
      authApiChange(valArr) {
        this.selectedApis = valArr;
      }
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss">
  .el-card__body {
    padding: 8px;
  }
</style>
